<template>
  <div>
    <a-modal v-model="showModal" @ok="confirmOk" @cancel="cancel" :title="titles" width="70%">
      <a-spin :spinning="loading">
        <a-form :form="form">
          <a-row :gutter="[24, 0]">
            <a-col :span="12">
              <a-form-item class="mb-15" label="拼团名称" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入' }] }]"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item class="mb-15" label="活动时间" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-range-picker
                  @change="onChange"
                  format="YYYY-MM-DD"
                  v-decorator="['time', { rules: [{ required: true, message: '请输入', type: 'array' }] }]"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[24, 0]">
            <a-col :span="12">
              <a-form-item class="mb-15" label="总限购数量" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input
                  v-decorator="['totalLimitCount', { rules: [{ required: true, message: '请输入' }] }]"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item class="mb-15" label="单次限购数量" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input
                  v-decorator="['singleLimitCount', { rules: [{ required: true, message: '请输入' }] }]"
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="[24, 0]">
            <a-col :span="12">
              <a-form-item class="mb-15" label="开团人数" :label-col="labelCol" :wrapper-col="wrapperCol">
                <div style="display: flex">
                  <a-input
                    placeholder="请输入"
                    v-decorator="[
                      'userSize',
                      {
                        rules: [{ required: true, message: '请输入' }],
                      },
                    ]"
                    maxLength="30"
                  ></a-input>
                </div>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item class="mb-15" label="限制时长（小时）" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input
                  placeholder="请输入"
                  v-decorator="[
                    'limitDuration',
                    {
                      rules: [{ required: true, message: '请输入' }],
                    },
                  ]"
                  maxLength="30"
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[24, 0]">
            <a-col :span="12">
              <a-form-item class="mb-15" label="是否虚拟开团" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-select
                  v-decorator="[
                    'virtualGroup',
                    {
                      rules: [{ required: true, message: '请输入', whitespace: true, type: 'boolean' }],
                    },
                  ]"
                >
                  <a-select-option :value="true"> 是 </a-select-option>
                  <a-select-option :value="false"> 否 </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item class="mb-15" label="状态" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-switch
                  checked-children="已上架"
                  un-checked-children="未上架"
                  v-decorator="['status', { valuePropName: 'checked' }]"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="[24, 0]">
            <a-col :span="12">
              <a-form-item class="mb-15" label="选择商品" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-input
                  v-decorator="[
                    'spuName',
                    {
                      rules: [{ required: true, message: '请输入', whitespace: true }],
                    },
                  ]"
                  disabled
                ></a-input>
                <a-button @click="selectGoods()" type="primary"> 选择 </a-button>
              </a-form-item>
              <GoodsList ref="goodsList" @choose="choose_goods"></GoodsList> </a-col
          ></a-row>

          <div>拼团商品：</div>
          <a-row :gutter="24">
            <a-col :span="24">
              <a-table class="mt-16 order-table" :columns="columns" :data-source="data" :pagination="false">
                <template #combinationPrice="combinationPrice, data">
                  <a-input placeholder="请输入" v-model="data.combinationPrice" />
                </template>
              </a-table>
            </a-col>
          </a-row>
        </a-form>
      </a-spin>
    </a-modal>
  </div>
</template>
<script>
import GoodsList from '@/components/GoodsList/index.vue'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { get } from 'lodash'
import { getSpugetdetail, upadteActivity, createActivity, getInfo } from '@/api/newPet'
import dayjs from 'dayjs'
export default {
  data() {
    return {
      loading: false,
      isShow: true,
      labelCol: {
        span: 8,
      },

      data: [],
      columns: [
        {
          title: '规格名称	',
          dataIndex: 'name',
          align: 'center',
          scopedSlots: {
            customRender: 'name',
          },
        },
        {
          title: '拼团价格',
          dataIndex: 'combinationPrice',
          align: 'center',
          scopedSlots: {
            customRender: 'combinationPrice',
          },
        },
      ],

      wrapperCol: {
        span: 16,
      },
      details: {},
      showModal: false,
      titles: '新增',
      info: {},
      spuId: 0,
      form: this.$form.createForm(this),
    }
  },
  computed: {},
  watch: {},
  async created() {},
  components: {
    quillEditor,
    GoodsList,
  },
  methods: {
    // 选择商品
    selectGoods() {
      this.$refs.goodsList.open()
    },
    onEditorBlur(quill) {
      console.log('editor blur!', quill)
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      console.log('editor focus!', quill)
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      console.log('editor ready!', quill)
    },
    // 内容改变事件，只需要这一个方法就够了
    onEditorChange({ quill, html, text }) {
      console.log('editor change!', quill, html, text)
      this.content = html
    },
    formgetFileLength(type) {
      //获取图片
      return get(this.form.getFieldValue(type), 'length') || 0
    },
    formuploadSuccess(data, type) {
      this.form.setFieldsValue({
        [type]: [data.path],
      })
    },
    changeSelect(e) {
      console.log(e)
    },
    // 修改拼团时间
    onChange(e) {
      console.log(e)
    },
    cancel() {
      this.form.resetFields()
      this.showModal = false
    },
    confirmOk() {
      this.form.validateFields((err, values) => {
        if (!err) {
          // this.loading = true
          const { info } = this
          if (values.time) {
            values.startTime = this.$utils.getStartTime(values.time[0])
            values.endTime = this.$utils.getEndTime(values.time[1])
          }
          console.log(this.form.getFieldValue())
          // return
          let data = {
            id: info && info.id ? info.id : undefined,
            ...this.$utils.trimValue(values),
            isEnabled: typeof values.isEnabled === 'undefined' ? true : values.isEnabled,
            spuId: this.spuId,
            products: this.data,
          }
          console.log(this.data)
          delete data.time

          let fun = info.id != undefined ? upadteActivity : createActivity
          fun(data)
            .then(() => {
              this.$message.success(info && info.id ? '修改成功！' : '新增成功！')
              this.$emit('upload')
              this.cancel()
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    async getDetails(id) {
      try {
        this.loading = true
        this.info = {}
        let res = await getInfo({ id: id })
        this.info = res
        this.$nextTick(() => {
          this.form.setFieldsValue({
            isEnabled: true,
            time: [dayjs(res.startTime).format('YYYY-MM-DD'), dayjs(res.endTime).format('YYYY-MM-DD')],
            ...res,
          })
          this.data = res.products?.map((i) => {
            return { ...i, name: i.skuName }
          })
        })
        this.loading = false
      } catch (error) {
        this.loading = false
        console.log(error)
      }
    },
    getData() {
      this.loading = true
      deductionDetail({
        id: 1,
      })
        .then((data) => {
          this.details = data
        })
        .finally(() => (this.loading = false))
    },
    open(data) {
      this.info = data

      if (data.id) {
        this.titles = '修改'
      } else {
        this.titles = '新增'
      }
      this.showModal = true
      // images:['https://img2.baidu.com/it/u=1906732828,3160455141&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=666']
      this.$nextTick(() => {
        this.form.setFieldsValue({
          isEnabled: true,
          time: [data.startTime, data.endTime],
          ...data,
        })
        this.data = data.products
      })
      // this.$emit('upload')
      // this.$nextTick(() => {
      //     this.form.setFieldsValue({
      // 					...res
      // 				})

      // 			})
    },
    open1(data) {
      if (data.id) {
        this.titles = '修改'
      } else {
        this.titles = '新增'
      }
      this.showModal = true
    },
    choose_goods(e) {
      if (e.id) {
        getSpugetdetail({
          id: e.id,
        }).then((res) => {
          this.form.setFieldsValue({
            spuName: res.name,
          })
          this.spuId = res.id
          for (let i = 0; i < res.skus.length; i++) {
            res.skus[i].spuId = res.id
            res.skus[i].skuId = res.skus[i].id
          }
          this.data = res.skus
          // for (let i = 0; i < res.skus.length; i++) {
          //   res.skus[i].spuId = res.id
          //   res.skus[i].skuId = res.skus[i].id
          // }
          // let arr = this.data && this.data.length > 0 ? this.data.concat(res.skus) : res.skus
          // //去重--不知道是不是需要
          // this.data = arr.reduce((accumulator, current) => {
          //   const duplicate = accumulator.find((item) => item.skuId === current.skuId && item.name === current.name)
          //   if (!duplicate) {
          //     return accumulator.concat([current])
          //   }
          //   return accumulator
          // }, [])
        })
      }
    },
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-form-item-label {
  // width: 100px;
}
</style>